import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import { saveAs } from 'file-saver'

// 定义全局的动画变量，一会用来关闭用
var downloadLoadingInstance

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // 判断响应类型是不是blob，如果是直接放行
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return res
    }

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 601: Illegal token;   614: Token expired;
      if (res.code === 601 || res.code === 614) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 异步编程模型，验证本次下载数据是不是json
async function blobValidate(data) {
  try {
    const text = await data.text()
    //  把字符串 尝试转解析json
    JSON.parse(text)
    return false
  } catch (error) {
    return true
  }
}

/** 通用文件下载 post提交
 * @param {Object} url  后台请求地址
 * @param {Object} data 请求参数
 * @param {Object} filename 保存本地的文件名
 */
export function download(url, data, filename) {
  // 自定义loading动画  https://element.eleme.cn/#/zh-CN/component/loading
  downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.6)' })

  // axios请求
  return service.post(url, data, {
    // 自定义格式，不是json,而是 key=value&key=value，后台不能使用@RequestBody
    transformRequest: [(data) => { return qs.stringify(data, { arrayFormat: 'repeat' }) }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 返回数据格式为 blob
    responseType: 'blob'
  }).then(async(data) => {
    // 判断数据是不是blob
    const isBlob = await blobValidate(data)

    if (isBlob) {
      const blob = new Blob([data])
      // 使用第三方插件保存
      saveAs(blob, filename)
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      // 取得报错信息
      const errMsg = rspObj.msg
      // 显示错误消息
      Message.error(errMsg)
    }
    // 关闭自定义load状态
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    // 关闭自定义load状态
    downloadLoadingInstance.close()
  })
}

export default service
